package cc.vv.lkimagecomponent2.downloadplugin;

import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import cc.vv.lkimagecomponent2.LKImage;
import cc.vv.lkimagecomponent2.glideLib.GlideApp;
import cc.vv.lklibrary.log.LogOperate;

/**
 * @author dupeng dupeng@vv.cc
 * @date 2018/5/3
 */

public class DownLoadPlugin {
    private static DownLoadPlugin instance;
    private final ExecutorService singleThreadExecutor;

    public static DownLoadPlugin getInstance() {
        if (instance == null) {
            synchronized (DownLoadPlugin.class) {
                if (instance == null) {
                    instance = new DownLoadPlugin();
                }
            }
        }
        return instance;
    }

    public DownLoadPlugin() {
        singleThreadExecutor = new ThreadPoolExecutor(1, 1,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
    }

    /**
     * 图片下载.
     *
     * @param url              图片地址
     * @param savefilePath     要保存到文件路径.  :不是文件夹路径,是图片文件路径.
     * @param downLoadCallback 下载回调: 回调是子线程.
     */
    public void downLoad(String url, final String savefilePath, final DownLoadCallback downLoadCallback) {
        GlideApp.with(LKImage.getContext()).download(url).into(new SimpleTarget<File>() {
            @Override
            public void onResourceReady(@NonNull final File resource, @Nullable Transition<? super File> transition) {
                if (resource != null && resource.exists()) {
                    final File file = new File(savefilePath);
                    if (singleThreadExecutor != null) {
                        singleThreadExecutor.submit(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    boolean b = copyFileUsingChannel(resource, file);
                                    if (b) {
                                        if (downLoadCallback != null) {
                                            downLoadCallback.onSuccess(savefilePath);
                                        }
                                    } else {
                                        if (downLoadCallback != null) {
                                            downLoadCallback.onFail(savefilePath);
                                        }
                                    }
                                } catch (Exception e) {
                                    LogOperate.eT(LKImage.TAG, e);
                                    if (downLoadCallback != null) {
                                        downLoadCallback.onFail(savefilePath);
                                    }
                                } finally {
                                    if (resource != null && resource.exists()) {
                                        resource.delete();
                                    }
                                }
                            }
                        });
                    } else {
                        LogOperate.eT(LKImage.TAG, "图片加载框架图片下载失败,原因:线程池为空!");
                    }
                }
            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
                if (downLoadCallback != null) {
                    downLoadCallback.onFail(savefilePath);
                }
            }

            @Override
            public void onLoadStarted(@Nullable Drawable placeholder) {
                super.onLoadStarted(placeholder);
                if (downLoadCallback != null) {
                    downLoadCallback.onStart(savefilePath);
                }
            }
        });
    }

    /**
     * 文件拷贝
     *
     * @param source
     * @param dest
     * @throws Exception
     */
    private boolean copyFileUsingChannel(File source, File dest) throws Exception {
        if (dest == null) {
            return false;
        }
        if (!dest.exists()) {
            boolean newFile = dest.createNewFile();
            if (!newFile) {
                return false;
            }
        }

        FileChannel sourceChannel = null;
        FileChannel destChannel = null;
        try {
            sourceChannel = new FileInputStream(source).getChannel();
            destChannel = new FileOutputStream(dest).getChannel();
            destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
            return true;
        } catch (Exception e) {
            LogOperate.eT(LKImage.TAG, "图片框架文件下载 后文件拷贝异常!", e);
            return false;
        } finally {
            sourceChannel.close();
            destChannel.close();
        }
    }
}
